package com.qianli.cashmama.trade.integration.product.impl;

import com.alibaba.fastjson.JSON;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.qianli.cashmama.product.facade.AppFacade;
import com.qianli.cashmama.product.facade.ProductFacade;
import com.qianli.cashmama.product.facade.result.AppPackageInfo;
import com.qianli.cashmama.product.facade.result.Product;
import com.qianli.cashmama.product.facade.result.ProductCategory;
import com.qianli.cashmama.trade.common.enums.TradeBorrowDurationEnum;
import com.qianli.cashmama.trade.integration.product.ProductIntegrationService;
import com.qianli.cashmama.trade.integration.product.dto.ProductDto;
import com.qianli.cashmama.trade.integration.product.dto.ProductRequestDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2017/7/20
 * Time: 下午5:39
 */
@Service
public class ProductIntegrationServiceImpl implements ProductIntegrationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProductIntegrationServiceImpl.class);

    //@MotanReferer(basicReferer = "basicRefererConfig", group = "motan_cashmama_product")
    @Autowired
    private ProductFacade productFacade;

    @Autowired
    private AppFacade appFacade;

    @Override
    public ProductDto getProductInfoByCode(String productCode) {
        try {
            Response<Product> productResponse = productFacade.getProductDetail(productCode, true);
            if (!productResponse.isSuccess() || productResponse.getData() == null) {
                return null;
            }
            return productToDto(productCode, productResponse.getData());
        } catch (Exception e) {
            LOGGER.error("== 获取产品信息失败 ==,productCode:{},e", productCode, e);
            return null;
        }
    }

    @Override
    public ProductCategory getCategoryByCode(String productCategory) {
        try {
            Response<ProductCategory> productCategoryResponse = productFacade.getCategoryByCode(productCategory);
            if (!productCategoryResponse.isSuccess() || productCategoryResponse.getData() == null) {
                return null;
            }
            return productCategoryResponse.getData();
        } catch (Exception e) {
            LOGGER.error("获取产品类目信息失败,productCategory:{},e", productCategory, e);
            return null;
        }
    }

    @Override
    public ProductCategory getCategoryByMerchantCode(String merchantCode) {
        Response<List<ProductCategory>> response = productFacade.getProductCategoriesByMerchantCode(merchantCode);
        if (response == null || !response.isSuccess() || CollectionUtils.isEmpty(response.getData())) {
            return null;
        }
        return response.getData().get(0);
    }

    @Override
    public Map<String, ProductDto> getProductDtoMap(List<String> productCodes) {
        Map<String, ProductDto> productDtoMap = new HashMap<>();
        Response<List<Product>> response = productFacade.getProductListDetail(productCodes, true);
        if (!response.isSuccess() || CollectionUtils.isEmpty(response.getData())) {
            return productDtoMap;
        }

        for (Product product : response.getData()) {
            productDtoMap.put(product.getCode(), productToDto(product.getCode(), product));
        }

        return productDtoMap;
    }

    @Override
    public AppPackageInfo getAppPackageInfoByPackageName(String packageName) {
        return appFacade.getAppPackageInfoByPackageName(packageName).getData();
    }

    @Override
    public ProductDto getSpecial2000Product(String productCategoryCode) {
        try {
            Response<Product> productResponse = productFacade.getProductByPrincipalMoneyAndPeriod(productCategoryCode, new BigDecimal("2000"), 7);
            if (!productResponse.isSuccess() || productResponse.getData() == null) {
                return null;
            }
            return productToDto(productResponse.getData().getCode(), productResponse.getData());
        } catch (Exception e) {
            LOGGER.error("获取特殊2000产品信息失败,productCode:{}", productCategoryCode, e);
            return null;
        }
    }

    /**
     * 获取金额最接近产品
     *
     * @param productCategoryCode
     * @param periodLength
     * @param borrowCapital
     * @return
     */
    @Override
    public ProductDto getSimilarProduct(String productCategoryCode, Integer periodLength, BigDecimal borrowCapital) {
        Response<List<Product>> response = productFacade.getActiveProductList(productCategoryCode, false);
        List<Product> productList = response.getData();
        if (CollectionUtils.isEmpty(productList)) {
            return null;
        }

        productList.sort(Comparator.comparingDouble(o -> Double.parseDouble(o.getPrincipalMoney())));
        Product product = null;

        LOGGER.info("111111111,{}", JSON.toJSONString(productList));

        borrowCapital = borrowCapital.setScale(2, BigDecimal.ROUND_HALF_UP);
        for (Product p : productList) {
            if (!p.getPaybackPeriodLength().equals(periodLength)) {
                continue;
            }
            if (new BigDecimal(p.getPrincipalMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).compareTo(borrowCapital) <= 0) {
                product = p;
            }
        }
        return product == null ? null : productToDto(product.getCode(), product);
    }

    private ProductDto productToDto(String productCode, Product product) {
        TradeBorrowDurationEnum tradeBorrowDurationEnum = TradeBorrowDurationEnum.convertByCode(product.getProductCategory().getPaybackPeriodUnit());
        return new ProductDto()
                .setProductCode(productCode)
                .setProductCategory(product.getProductCategory().getCode())
                .setStatus(product.getActive() ? 1 : 0)
                .setBorrowTotalCapital(new BigDecimal(product.getPrincipalMoney()))
                .setReceivedTotalCapital(new BigDecimal(product.getArrivalMoney()))
                .setTotalServiceFee(new BigDecimal(product.getServiceCharge()))
                .setBorrowRatio(new BigDecimal(product.getRate()))
                .setTotalPeriod(product.getTotalPaybackPeriodCount())
                .setBorrowDuration(tradeBorrowDurationEnum.getType())
                .setPeriodLength(product.getPaybackPeriodLength())
                .setOverdueServiceFee(new BigDecimal(product.getOverdueServiceCharge()))
                .setOverdueRatio(new BigDecimal(product.getPenaltyRate()))
                .setGstCharge(new BigDecimal(product.getGstCharge()));
    }

    @Override
    public ProductDto getProductDetailByArrivalMoney(ProductRequestDTO requestDTO) {

        return null;
    }
}
